﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using StartMVC.Models;
using System.Web.Mvc;
using System.Net.Mail;

namespace StartMVC.Controllers
{
    public class MemberController : BaseController
    {

        private string pwSalt = "abcdefghijklmnopqrstuvwxyz";
       
        //会员注册页面
        public ActionResult Register()
        {
            return View();
        }

        //写入会员信息
        //由于view中移除了这两个字段 因此此处需要加上这段
        [HttpPost]
        public ActionResult Register([Bind(Exclude = "RegisterOn,Authcode")]Member member)
        {
            //return View();
            //检测会员是否存在
            var chk_member = db.Members.Where(p => p.Email == member.Email).FirstOrDefault();
            if (chk_member!=null)
            {
                ModelState.AddModelError("Email", "该Email已经被注册");
            }
            if (ModelState.IsValid)
            {
                member.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(pwSalt + member.Password, "SHA1");
                member.RegisterOn = DateTime.Now;
                member.Authcode = Guid.NewGuid().ToString();
                db.Members.Add(member);
                db.SaveChanges();

                SendAuthCodeToMember(member);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return View();
            }
            
            
        }

        private void SendAuthCodeToMember(Member member)
        {
           // throw new NotImplementedException();
            string mailbody = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/MemberRegisterEmailTemplate.html"));

            mailbody = mailbody.Replace("{{Name}}", member.Name);
            mailbody = mailbody.Replace("{{RegisterOn}}", member.RegisterOn.ToString("F"));

            var autl_url = new UriBuilder(Request.Url)
            {
                Path = Url.Action("ValidateRegister", new { id = member.Authcode }),
                Query = ""
            };
            mailbody = mailbody.Replace("{{AUTH_URL}}", autl_url.ToString());
            try
            {
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("forliangliangtest@gmail.com", "forliangliangtest111");
                SmtpServer.EnableSsl = true;

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress("forliangliangtest@gmail.com");
                mail.To.Add(member.Email);
                mail.Subject = "会员注册确认信";
                mail.Body = mailbody;
                mail.IsBodyHtml = true;
                SmtpServer.Send(mail);
                db.MailLogs.Add(new MailLog() { SendTime = DateTime.Now, IsSendOk = true, Msg = string.Empty, Member = member });
                db.SaveChanges();
            }
            catch (System.Exception ex)
            {
                string msg = ex.Message;
                db.MailLogs.Add(new MailLog() { SendTime = DateTime.Now, IsSendOk = false, Msg = msg, Member = member });
                db.SaveChanges();
            }
            
        }

        //显示会员登录页面
        public ActionResult Login(string returnurl)
        {
            ViewBag.ReturnUrl = returnurl;
            return View();
        }
        //运行会员登录
        [HttpPost]
        public ActionResult Login(string email, string password, string returnurl)
        {
            if (ValidateUser(email, password))
            {
                FormsAuthentication.SetAuthCookie(email, false);

                if (String.IsNullOrEmpty(returnurl))
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                    return Redirect(returnurl);
            }
            ModelState.AddModelError("", "您输入的帐号或密码错误");
            return View();
        }


        public ActionResult ValidateRegister(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return HttpNotFound();
            }
            var member = db.Members.Where(p => p.Authcode == id).FirstOrDefault();
            if (member!=null)
            {
                TempData["LastTempMessage"] = "会员验证成功,您可以登录了";
                member.Authcode = null;
                db.SaveChanges();
            }
            else
            {
                TempData["LastTempMessage"] = "查无此会员验证码,您可能已经登录过了";
            }
            return RedirectToAction("Login", "Member");
        }


        private bool ValidateUser(string email, string password)
        {
           // throw new NotImplementedException();
            var hash_pw = FormsAuthentication.HashPasswordForStoringInConfigFile(pwSalt + password, "SHA1");
            var member = (from p in db.Members
                          where p.Email == email && p.Password == hash_pw
                          select p
                            ).FirstOrDefault();
            //return member != null;
            if(member!=null)
            {
                if (member.Authcode==null)
                {
                    return true;
                }
                else
                {
                    ModelState.AddModelError("", "您尚未通过会员验证,请收信并点击会员链接");
                    return false;
                }
            }
            else
            {
                ModelState.AddModelError("", "您的账号或密码错误");
                return false;
            }
        }
        //运行会员注销
        public ActionResult Logout()
        {
            //清除窗体验证的Cookies
            FormsAuthentication.SignOut();

            //清除所有曾经写入的session信息
            Session.Clear();
            return View();
        }
        //检测用户Email地址是否重复
        [HttpPost]
        public ActionResult CheckDup(string Email)
        {
            var member = db.Members.Where(m => m.Email == Email).ToList();
            if (member.Count>0)
            {
                return Json(false);
            }
            else
                return Json(true);
        }
    }
}
